package com.lzy.cloud.push.umeng.util;

import com.lzy.cloud.push.request.UMengParam;
import com.lzy.cloud.push.umeng.android.AndroidBroadcast;
import com.lzy.cloud.push.umeng.android.AndroidGroupcast;
import com.lzy.cloud.push.umeng.android.AndroidUnicast;
import com.lzy.cloud.push.umeng.base.AndroidNotification;
import com.lzy.cloud.push.umeng.base.PushClient;
import com.lzy.cloud.push.umeng.ios.IOSBroadcast;
import com.lzy.cloud.push.umeng.ios.IOSGroupcast;
import com.lzy.cloud.push.umeng.ios.IOSUnicast;
import com.lzy.framework.core.ensure.Ensure;
import com.lzy.framework.core.utils.StringUtil;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 该类封装了常用的发送通知方法，若想更细粒度的发送，可以使用youMeng包下的其他类自定义
 * see: developer.umeng.com/docs/66632/detail/68343#h2-u540Du8BCDu89E3u91CA2
 */
@Component
public class UMengUtil {


    private final static Logger LOGGER = LoggerFactory.getLogger(UMengUtil.class);

    @Autowired
    private PushClient pushClient;

    /**
     * 根据tag集合发送推送
     *
     * @param tags
     * @return
     */
    public Map<String, Object> sendMessageByTag(String[] tags, UMengParam uMengParam) throws Exception {
        JSONObject whereObject = new JSONObject();
        JSONArray tagArray = new JSONArray();
        for (String tag : tags) {
            JSONObject tagJson = new JSONObject();
            tagJson.put("tag", tag);
            tagArray.put(tagJson);
        }
        JSONObject orJson = new JSONObject();
        orJson.put("or", tagArray);
        JSONObject andJson = new JSONObject();
        andJson.put("and", orJson);
        whereObject.put("where", andJson);
        uMengParam.setFilter(whereObject);
        return groupcast(uMengParam);
    }

    /**
     * 向满足特定条件的设备集合发送消息，例如: “特定版本”、”特定地域”等
     *
     * @return
     */
    public Map<String, Object> groupcast(UMengParam uMengParam) {
        Ensure.that(uMengParam.getFilter() != null && StringUtil.isNotBlank(uMengParam.getTitle()) && StringUtil.isNotBlank(uMengParam.getTicker()) && StringUtil.isNotBlank(uMengParam.getText())).isTrue("10000033");
        AndroidBroadcast.AfterOpenAction androidAfterOpen = null;
        for (AndroidBroadcast.AfterOpenAction afterOpenAction : AndroidBroadcast.AfterOpenAction.values()) {
            if (uMengParam.getAfterOpen().equals(afterOpenAction.toString())) {
                androidAfterOpen = afterOpenAction;
                break;
            }
        }
        AndroidNotification.DisplayType displayType = null;
        for (AndroidNotification.DisplayType displayType1 : AndroidNotification.DisplayType.values()) {
            if (uMengParam.getDisplayType().equals(displayType1.getValue())) {
                displayType = displayType1;
                break;
            }
        }
        Ensure.that(androidAfterOpen != null).isTrue("10000033");
        Map<String, Object> result = new HashMap<>();
        try {
            AndroidGroupcast androidGroupcast = new AndroidGroupcast();
            androidGroupcast.setTitle(uMengParam.getTitle());
            androidGroupcast.setTicker(uMengParam.getTicker());
            androidGroupcast.setAfterOpenAction(androidAfterOpen);
            androidGroupcast.setActivity(uMengParam.getActivity());
            androidGroupcast.setDisplayType(displayType);
            androidGroupcast.setText(uMengParam.getText());
            if (!uMengParam.getProductionMode()) {
                androidGroupcast.setProductionMode();
            }
            androidGroupcast.setUrl(uMengParam.getUrl());
            androidGroupcast.setFilter(uMengParam.getFilter());
            IOSGroupcast iosGroupcast = new IOSGroupcast();
            iosGroupcast.setAlert(uMengParam.getText());
            /**
             * 角标数
             */
            iosGroupcast.setBadge(1);
            if (!uMengParam.getProductionMode()) {
                iosGroupcast.setPredefinedKeyValue("production_mode", "false");
            }
            iosGroupcast.setFilter(uMengParam.getFilter());
            result.put("android", pushClient.send(androidGroupcast));
            result.put("ios", pushClient.send(iosGroupcast));
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            LOGGER.error("组播发送失败！");
        }
        return result;
    }

    /**
     * 向指定的设备发送消息
     *
     * @return
     */
    public String unicast(UMengParam uMengParam) {
        Ensure.that(null != uMengParam.getDeviceType()
                && (uMengParam.getDeviceType().equals(1) || uMengParam.getDeviceType().equals(2))
                && StringUtil.isNotBlank(uMengParam.getDeviceToken())
                && StringUtil.isNotBlank(uMengParam.getTitle())
                && StringUtil.isNotBlank(uMengParam.getTicker())
                && StringUtil.isNotBlank(uMengParam.getText())).isTrue("10000033");
        AndroidBroadcast.AfterOpenAction androidAfterOpen = null;
        for (AndroidBroadcast.AfterOpenAction afterOpenAction : AndroidBroadcast.AfterOpenAction.values()) {
            if (uMengParam.getAfterOpen().equals(afterOpenAction.toString())) {
                androidAfterOpen = afterOpenAction;
                break;
            }
        }
        AndroidNotification.DisplayType displayType = null;
        for (AndroidNotification.DisplayType displayType1 : AndroidNotification.DisplayType.values()) {
            if (uMengParam.getDisplayType().equals(displayType1.getValue())) {
                displayType = displayType1;
                break;
            }
        }
        Ensure.that(androidAfterOpen != null).isTrue("10000033");
        try {
            if (uMengParam.getDeviceType().equals(1)) {
                AndroidUnicast androidUnicast = new AndroidUnicast();
                androidUnicast.setTitle(uMengParam.getTitle());
                androidUnicast.setTicker(uMengParam.getTicker());
                androidUnicast.setAfterOpenAction(androidAfterOpen);
                androidUnicast.setActivity(uMengParam.getActivity());
                androidUnicast.setDisplayType(displayType);
                androidUnicast.setText(uMengParam.getText());
                if (!uMengParam.getProductionMode()) {
                    androidUnicast.setPredefinedKeyValue("production_mode", "false");
                }
                androidUnicast.setSound(uMengParam.getSound());
                androidUnicast.setUrl(uMengParam.getUrl());
                androidUnicast.setDeviceToken(uMengParam.getDeviceToken());
                return pushClient.send(androidUnicast);
            } else {
                IOSUnicast iosUnicast = new IOSUnicast();
                iosUnicast.setAlert(uMengParam.getText());
                /**
                 * 角标数
                 */
                iosUnicast.setBadge(1);
                if (!uMengParam.getProductionMode()) {
                    iosUnicast.setPredefinedKeyValue("production_mode", "false");
                }
                iosUnicast.setSound(uMengParam.getSound());
                iosUnicast.setDeviceToken(uMengParam.getDeviceToken());
                return pushClient.send(iosUnicast);
            }
        } catch (Exception e) {
            LOGGER.error("发送失败---" + e.getMessage());
            Ensure.that(true).isFalse("");
            return null;
        }
    }


    /**
     * 向指定的一批设备发送消息
     * todo
     *
     * @return
     */
    public String listcast(UMengParam uMengParam) {
        return null;
    }

    /**
     * 向安装该App的所有设备发送消息
     *
     * @return
     */
    public Map<String, Object> broadcast(UMengParam uMengParam) {
        Ensure.that(StringUtil.isNotBlank(uMengParam.getTitle()) && StringUtil.isNotBlank(uMengParam.getTicker()) && StringUtil.isNotBlank(uMengParam.getText())).isTrue("10000033");
        AndroidBroadcast.AfterOpenAction androidAfterOpen = null;
        for (AndroidBroadcast.AfterOpenAction afterOpenAction : AndroidBroadcast.AfterOpenAction.values()) {
            if (uMengParam.getAfterOpen().equals(afterOpenAction.toString())) {
                androidAfterOpen = afterOpenAction;
                break;
            }
        }
        AndroidNotification.DisplayType displayType = null;
        for (AndroidNotification.DisplayType displayType1 : AndroidNotification.DisplayType.values()) {
            if (uMengParam.getDisplayType().equals(displayType1.getValue())) {
                displayType = displayType1;
                break;
            }
        }
        Ensure.that(androidAfterOpen != null).isTrue("10000033");
        Map<String, Object> result = new HashMap<>();
        try {
            AndroidBroadcast androidBroadcast = new AndroidBroadcast();
            androidBroadcast.setTitle(uMengParam.getTitle());
            androidBroadcast.setTicker(uMengParam.getTicker());
            androidBroadcast.setAfterOpenAction(androidAfterOpen);
            androidBroadcast.setActivity(uMengParam.getActivity());
            androidBroadcast.setDisplayType(displayType);
            androidBroadcast.setText(uMengParam.getText());
            if (!uMengParam.getProductionMode()) {
                androidBroadcast.setProductionMode();
            }
            androidBroadcast.setUrl(uMengParam.getUrl());
            IOSBroadcast iosBroadcast = new IOSBroadcast();
            iosBroadcast.setAlert(uMengParam.getText());
            iosBroadcast.setBadge(1);//角标数
            if (!uMengParam.getProductionMode()) {
                iosBroadcast.setProductionMode();
            }
            result.put("android", pushClient.send(androidBroadcast));
            result.put("ios", pushClient.send(iosBroadcast));
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            LOGGER.error("广播发送失败！");
        }
        return result;
    }

    /**
     * 开发者将批量的device_token或者alias存放到文件，通过文件ID进行消息发送
     * todo
     *
     * @return
     */
    public String filecast() {
        return "";
    }


}
